package com.yuehuanghun.admin.generator.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.groups.Default;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yuehuanghun.admin.generator.domain.GenTable;
import com.yuehuanghun.admin.generator.domain.GenTableColumn;
import com.yuehuanghun.admin.generator.service.IGenTableColumnService;
import com.yuehuanghun.admin.generator.service.IGenTableService;
import com.yuehuanghun.framework.annotation.Log;
import com.yuehuanghun.framework.annotation.Log.BusinessType;
import com.yuehuanghun.framework.domain.PageDTO;
import com.yuehuanghun.framework.domain.validate.group.Add;
import com.yuehuanghun.framework.util.text.Convert;
import com.yuehuanghun.framework.web.BaseResource;
import com.yuehuanghun.mybatis.milu.data.Sort;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;

/**
 * 代码生成 操作处理
 * 
 * @author yadmin
 */
@RestController
@RequestMapping("/tool/gen")
@SaCheckLogin
public class GenController extends BaseResource {
	@Autowired
	private IGenTableService genTableService;

	@Autowired
	private IGenTableColumnService genTableColumnService;

	/**
	 * 查询代码生成列表
	 */
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	@SaCheckPermission("tool:gen:list")
	public PageDTO<GenTable> genList(GenTable genTable) {
		List<GenTable> list = genTableService.getByExampleAndSort(genTable, Sort.desc(GenTable::getTableId), getPage());
		return toPage(list);
	}

	/**
	 * 修改代码生成业务
	 */
	@GetMapping(value = "/{talbleId}")
	@SaCheckPermission("tool:gen:query")
	public Map<String, Object> getInfo(@PathVariable @Validated({Default.class, Add.class}) Long talbleId) {
		GenTable table = genTableService.selectGenTableById(talbleId);
//		List<GenTable> tables = genTableService.selectGenTableAll();
		List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
		Map<String, Object> map = new HashMap<>();
		map.put("info", table);
		map.put("rows", list);
//		map.put("tables", tables);
		return map;
	}

	/**
	 * 查询数据库列表
	 */
	@GetMapping("/db/list")
	@SaCheckPermission("tool:gen:list")
	public PageDTO<GenTable> dataList(GenTable genTable) {
		startPage();
		List<GenTable> list = genTableService.selectDbTableList(genTable);
		return toPage(list);
	}

	/**
	 * 查询数据表字段列表
	 */
	@GetMapping(value = "/column/{talbleId}")
	@SaCheckPermission("tool:gen:list")
	public PageDTO<GenTableColumn> columnList(Long tableId) {
		List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
		return toPage(0, 0, list.size(), list);
	}

	/**
	 * 导入表结构（保存）
	 */
	@Log(title = "代码生成", businessType = BusinessType.IMPORT)
	@PostMapping("/importTable")
//	@SaCheckPermission("tool:gen:list")
	public void importTableSave(String tables) {
		genTableService.importGenTable(Convert.toStrArray(tables));
	}

	/**
	 * 修改保存代码生成业务
	 */
	@Log(title = "代码生成", businessType = BusinessType.UPDATE)
	@PutMapping
	@SaCheckPermission("tool:gen:edit")
	public void editSave(@Validated @RequestBody GenTable genTable) {
		genTableService.validateEdit(genTable);
		genTableService.updateGenTable(genTable);
	}

	/**
	 * 删除代码生成
	 */
	@Log(title = "代码生成", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tableIds}")
	@SaCheckPermission("tool:gen:remove")
	public void remove(@PathVariable Long[] tableIds) {
		genTableService.deleteGenTableByIds(tableIds);
	}

	/**
	 * 预览代码
	 */
	@GetMapping("/preview/{tableId}")
	@SaCheckPermission("tool:gen:preview")
	public Map<String, String> preview(@PathVariable("tableId") Long tableId) throws IOException {
		return genTableService.previewCode(tableId);
	}

	/**
	 * 生成代码（下载方式）
	 */
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/download/{tableName}")
//	@SaCheckPermission("tool:gen:code")
	public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
		byte[] data = genTableService.downloadCode(tableName);
		genCode(response, data);
	}

	/**
	 * 生成代码（自定义路径）
	 */
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/genCode/{tableName}")
	@SaCheckPermission("tool:gen:code")
	public void genCode(@PathVariable("tableName") String tableName) {
		genTableService.generatorCode(tableName);
	}

	/**
	 * 同步数据库
	 */
	@Log(title = "代码生成", businessType = BusinessType.UPDATE)
	@GetMapping("/synchDb/{tableName}")
	@SaCheckPermission("tool:gen:edit")
	public void synchDb(@PathVariable("tableName") String tableName) {
		genTableService.synchDb(tableName);
	}

	/**
	 * 批量生成代码
	 */
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/batchGenCode")
	@SaCheckPermission("tool:gen:code")
	public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
		String[] tableNames = Convert.toStrArray(tables);
		byte[] data = genTableService.downloadCode(tableNames);
		genCode(response, data);
	}

	/**
	 * 生成zip文件
	 */
	private void genCode(HttpServletResponse response, byte[] data) throws IOException {
		response.reset();
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
		response.setHeader("Content-Disposition", "attachment; filename=\"codes.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IOUtils.write(data, response.getOutputStream());
	}
}